<?php

/**
 * Description of Application
 *
 * @author ervinne
 */
class Application {

    protected $controller_name = APPLICATION_HOME_PAGE;
    protected $controller_method_name = "index";
    protected $parameters = [];
    protected $controller;

    public function __construct() {
        $url = $this->parse_url();

        if (isset($url[0]) && file_exists(dirname(__FILE__) . "/../controllers/{$url[0]}.php")) {
            $this->controller_name = $url[0];
            unset($url[0]);
        }

        require_once dirname(__FILE__) . "/../controllers/{$this->controller_name}.php";
        $this->controller = new $this->controller_name;

        if (isset($url[1])) {
            if (method_exists($this->controller, $this->controller_method_name)) {
                $this->controller_method_name = $url[1];
                unset($url[1]);
            }
        }

        $this->parameters = $url ? array_values($url) : [];
        
        call_user_func_array(
                [$this->controller, $this->controller_method_name], $this->parameters);
    }

    protected function parse_url() {
        if (isset($_GET["url"])) {
            return $url = explode("/", filter_var(rtrim($_GET["url"], "/"), FILTER_SANITIZE_URL));
        }

        return [];
    }

}
